const User        = require('../models').User;
const Op          = require('../models').Sequelize.Op;
const md5         = require('./../utils/md5');
const {createToken, verifyToken} = require('./../utils/token');

module.exports = {
    /**
     * 获取所有用户
     * @param {*} req 
     * @param {*} res 
     * @returns 
     */
    async listAll(req, res) {
        return await User.findAndCountAll({
            order: [['id', 'desc']],
			attributes: {exclude: ['password']},
            limit: req.query.pageSize || 15,
            offset: req.query.curPage * req.query.pageSize || 0,
            where: {
                name: {
                    [Op.like]: '%' + req.query.name + '%'
                }
            }
        }).then(users => res.json(users))
    },

    /**
     * 根据id获取用户
     * @param {*} req 
     * @param {*} res 
     * @returns 
     */
    async getById(req, res) {
        return await User
            .findByPk(req.params.id, {
                attributes: {exclude: ['password']},
            })
            .then((user) => {
                if (!user) {
                    return res.status(404).send({
                        success: false,
                        message: 'User Not Found',
                    });
                }
                return res.status(200).send(user);
            })
            .catch((error) => res.status(400).send(error));
    },

    /**
     * 创建用户
     * @param {*} req 
     * @param {*} res 
     */
    async create(req, res) {
        await User.findOne({
            where: {
                name: req.body.name
            }
        })
        .then((user) => {
            if (user) {
                return res.status(200).send({
                    success: false,
                    message: 'User has existed',
                });
            }
            return User
                .create({
                    name       : req.body.name,
                    password   : md5(req.body.password),
                    role       : req.body.role,
                    description: req.body.description || '平台用户',
                    active     : false
                })
                .then((user) => res.status(201).send({
                    success: true,
                    user: user.id
                }))
                .catch((error) => res.status(400).send(error));
        })
        .catch((error) => res.status(400).send(error));
    },

    /**
     * 用户登录
     * @param {*} req 
     * @param {*} res 
     */
    async login(req, res){
        await User.findOne({
            where: {
                name: req.body.name
            }
        })
        .then((user) => {
            // 如果用户不存在
            if (!user) {
                return res.status(200).send({
                    success: false,
                    message: 'User Not Found',
                });
            }
            // 如果用户存在，则比对密码
            var pwd = md5(req.body.password);
            if(user.password === pwd){
                var token = createToken({id: user.id, name: user.name, role: user.role, active: user.active});
                return res.status(200).send({
                    success: true,
                    token: token
                });
            }else{
                // 密码不正确
                return res.status(200).send({
                    success: false,
                    message: 'Password is wrong',
                });
            }
            
        })
        .catch((error) => res.status(400).send(error));
    },
    /**
     * 更新用户信息
     * @param {*} req 
     * @param {*} res 
     * @returns 
     */
    async update(req, res) {
        return await User
            .findByPk(req.params.id)
            .then(user => {
                if (!user) {
                    return res.status(200).send({
                        success: false,
                        message: 'User Not Found',
                    });
                }
                return user
                    .update({
                        name       : req.body.name || user.name,
                        password   : req.body.password || user.password,
                        role       : req.body.role || user.role,
                        description: req.body.description || user.description,
                        complete   : req.body.complete || user.complete,
                        active     : req.body.active ? req.body.active : ( !req.body.active ? req.body.active : user.active)
                    })
                    .then(() => res.status(200).send(user))
                    .catch((error) => res.status(400).send(error));
            })
            .catch((error) => res.status(400).send(error));
    },

    async delete(req, res) {
        return await User
            .findByPk(req.params.id)
            .then(user => {
                if (!user) {
                    return res.status(200).send({
                        success: false,
                        message: 'User Not Found',
                    });
                }else{
                    return user
                        .destroy()
                        .then(() => res.status(200).send({
                            success: true,
                            message: 'delete successful'
                        }))
                        .catch((error) => res.status(400).send(error));
                }
            })
            .catch((error) => res.status(400).send(error));
    },
}